//
// Created on 2022/11/15.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include <js_native_api.h>
#include "../include/WorkDemo.h"
#include <string>
#include <node_api.h>
#include <hilog/log.h>
#include "math.h"
#include "../include/ClassBind.h"

#define LOG_DOMAIN 0
#define LOG_TAG "demoTest"

napi_value ClassBind::JsConstructor(napi_env env, napi_callback_info info){
    OH_LOG_INFO(LOG_APP, "js constructor triggered");
    napi_value targetObj = nullptr;
    void *data = nullptr;
    size_t argsNum = 2;
    napi_value args[2] = {nullptr};
    
    napi_get_cb_info(env, info, &argsNum, args ,&targetObj, &data);
    ClassBind *classBind = new ClassBind();
    napi_get_value_double(env, args[0], &classBind->a);
    napi_get_value_double(env, args[1], &classBind->b);
    
    napi_set_named_property(env, targetObj, "num1", args[0]);
    napi_set_named_property(env, targetObj, "num2", args[1]);
    
    napi_wrap(env, targetObj, classBind, [](napi_env env, void *data, void *hint){
            ClassBind *bind = (ClassBind *)data;
            delete bind;
            bind = nullptr;
        },
        nullptr, nullptr);
    OH_LOG_INFO(LOG_APP, "a is %{public}f, b is %{public}f", classBind->a, classBind->b);
    return targetObj;
}

napi_value ClassBind::JsOperate(napi_env env, napi_callback_info info){
    OH_LOG_INFO(LOG_APP, "js JsOperate");
    napi_value args[1] = {nullptr};
    size_t argsNum = 1;
    napi_value context = nullptr;
    napi_get_cb_info(env, info, &argsNum, args, &context, nullptr);
    ClassBind *classBind = nullptr;
    napi_unwrap(env, context, (void **)&classBind);
    uint32_t operateType = 0;
    napi_get_value_uint32(env, args[0], &operateType);
    double result = 0;
    OH_LOG_INFO(LOG_APP, "js operateType step1 operateType %{public}f", operateType);
    if(operateType == 2){
        OH_LOG_INFO(LOG_APP, "js operateType = 2");
        result = classBind->a+classBind->b;
    }
    napi_value res = nullptr;
    napi_create_double(env, result, &res);
    return res;
}